<template>
    <div class="app-container">
        <!-- 搜索和操作区域 -->
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
            <el-form-item label="课程名称">
                <el-input v-model="searchForm.courseName" placeholder="请输入课程名称"></el-input>
            </el-form-item>
            <el-form-item label="课程编号">
                <el-input v-model="searchForm.courseNo" placeholder="请输入课程编号"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSearch">查询 <el-icon class="el-icon--right"><Search /></el-icon></el-button>
                <el-button type="success" @click="handleAdd">新增课程 <el-icon class="el-icon--right"><Plus /></el-icon></el-button>
            </el-form-item>
        </el-form>

        <!-- 课程列表 -->
        <el-table v-loading="listLoading" :data="filteredList" element-loading-text="Loading" border fit highlight-current-row>
            <el-table-column align="center" label="ID" width="80px">
                <template #default="scope">
                    {{ scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column label="课程编号" prop="courseNo" align="center">
                <template #default="scope">
                    {{ scope.row.courseNo }}
                </template>
            </el-table-column>
            <el-table-column label="课程名称" prop="courseName" align="center">
                <template #default="scope">
                    <span>{{ scope.row.courseName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="课程属性" prop="courseAttr" align="center">
                <template #default="scope">
                    <span>{{ getCourseAttrText(scope.row.courseAttr) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="备注" prop="remark" align="center">
                <template #default="scope">
                    <span>{{ scope.row.remark || '-' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createdTime" align="center" width="180px">
                <template #default="scope">
                    <span>{{ scope.row.createdTime }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="200px">
                <template #default="scope">
                    <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑 <el-icon class="el-icon--right"><Edit /></el-icon></el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除 <el-icon class="el-icon--right"><Delete /></el-icon></el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 新增/编辑课程对话框 -->
        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="40%">
            <el-form :model="courseForm" :rules="rules" ref="formRef" label-width="100px">
                <el-form-item label="课程编号" prop="courseNo">
                    <el-input v-model="courseForm.courseNo" :disabled="isEdit" placeholder="请输入课程编号"></el-input>
                </el-form-item>
                <el-form-item label="课程名称" prop="courseName">
                    <el-input v-model="courseForm.courseName" placeholder="请输入课程名称"></el-input>
                </el-form-item>
                <el-form-item label="课程属性" prop="courseAttr">
                    <el-select v-model="courseForm.courseAttr" placeholder="请选择课程属性" style="width: 100%">
                        <el-option label="理论课" value="01"></el-option>
                        <el-option label="实验课" value="02"></el-option>
                        <el-option label="实践课" value="03"></el-option>
                        <el-option label="体育课" value="04"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="courseForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue';
import axios from 'axios';

const list = ref([]);
const listLoading = ref(true);

const searchForm = ref({
    courseName: '',
    courseNo: '',
});

const dialogVisible = ref(false);
const dialogTitle = ref('');
const isEdit = ref(false);
const formRef = ref(null);

const rules = {
    courseNo: [
        { required: true, message: '请输入课程编号', trigger: 'blur' },
        { min: 1, max: 20, message: '课程编号长度在 1 到 20 个字符', trigger: 'blur' }
    ],
    courseName: [
        { required: true, message: '请输入课程名称', trigger: 'blur' },
        { min: 1, max: 100, message: '课程名称长度在 1 到 100 个字符', trigger: 'blur' }
    ],
    courseAttr: [
        { required: true, message: '请选择课程属性', trigger: 'change' }
    ]
};

const courseForm = ref({
    id: null,
    courseNo: '',
    courseName: '',
    courseAttr: '',
    remark: '',
});

const filteredList = computed(() => {
    if (!list.value) return [];
    return list.value.filter(item => {
        const nameMatch = searchForm.value.courseName ? item.courseName.includes(searchForm.value.courseName) : true;
        const noMatch = searchForm.value.courseNo ? item.courseNo.includes(searchForm.value.courseNo) : true;
        return nameMatch && noMatch;
    });
});

const getList = async () => {
    listLoading.value = true;
    try {
        const response = await axios.get('/api/course/getList', {
            headers: {
                "token": localStorage.getItem("token"),
            },
        });
        list.value = response.data.data || [];
        if (list.value.length === 0) {
            ElMessage.success("暂无课程信息");
        }
    } catch (error) {
        console.error('Failed to fetch list:', error);
        ElMessage.error('获取课程列表失败');
    } finally {
        listLoading.value = false;
    }
};

const handleSearch = () => {
    // 前端过滤，无需重新请求
};

const handleAdd = () => {
    isEdit.value = false;
    dialogTitle.value = '新增课程';
    courseForm.value = {
        id: null,
        courseNo: '',
        courseName: '',
        courseAttr: '',
        remark: '',
    };
    dialogVisible.value = true;
};

const handleEdit = (row) => {
    isEdit.value = true;
    dialogTitle.value = '编辑课程';
    courseForm.value = { ...row };
    dialogVisible.value = true;
};

const submitForm = async () => {
    try {
        await formRef.value.validate();
        
        if (isEdit.value) {
            await axios.put(`/api/course/update/${courseForm.value.id}`, courseForm.value, {
                headers: {
                    "token": localStorage.getItem("token"),
                },
            });
            ElMessage.success('更新成功');
        } else {
            await axios.post('/api/course/add', courseForm.value, {
                headers: {
                    "token": localStorage.getItem("token"),
                },
            });
            ElMessage.success('新增成功');
        }
        dialogVisible.value = false;
        await getList();
    } catch (error) {
        console.error('Form submission error:', error);
        ElMessage.error(isEdit.value ? '更新失败' : '新增失败');
    }
};

const handleDelete = (row) => {
    ElMessageBox.confirm(`确定删除课程 ${row.courseName} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        try {
            await axios.delete(`/api/course/delete/${row.id}`, {
                headers: {
                    "token": localStorage.getItem("token"),
                },
            });
            ElMessage.success('删除成功');
            await getList();
        } catch (error) {
            console.error('Delete error:', error);
            ElMessage.error('删除失败');
        }
    }).catch(() => {
        // 用户取消操作
    });
};

const getCourseAttrText = (attrCode) => {
    const attrMap = {
        '01': '理论课',
        '02': '实验课', 
        '03': '实践课',
        '04': '体育课'
    };
    return attrMap[attrCode] || attrCode;
};

onMounted(() => {
    getList();
});

</script>

<style scoped>
.app-container {
    padding: 20px;
}
.demo-form-inline .el-input {
    width: 180px;
}
.dialog-footer {
    text-align: right;
}
</style>